import {
  createUserData,
  deleteUserById,
  editUserData,
  postUsersListData
} from '@/service/user/user'
import type { IuserList } from '@/types/user/user'
import { notification } from '@/utils/notification'
import { defineStore } from 'pinia'

const useUserStore = defineStore('user', {
  state: () => ({
    userList: [] as IuserList[],
    totalCount: 0
  }),
  actions: {
    // 用户列表
    async postUsersListDataAction(data?: any) {
      // 1.获取用户列表数据
      const userListRes = await postUsersListData(data)

      // 2.存储用户列表数据
      const { list, totalCount } = userListRes.data
      this.userList = list
      this.totalCount = totalCount
    },
    // 删除用户
    async deleteUserByIdAction(id: number) {
      // 1.调用接口
      const deleteUserRes = await deleteUserById(id)

      // 2.消息提示
      if (deleteUserRes.code === 0) {
        // 2.1删除成功
        notification('success', deleteUserRes.data)
        // 2.2请求新的数据
        this.postUsersListDataAction({ size: 10, offset: 0 })
      } else {
        //2.3删除失败
        notification('error', deleteUserRes.data)
      }
    },
    // 新建用户
    async createUserDataAction(userInfo: any) {
      // 1.调用接口
      const createUserRes = await createUserData(userInfo)

      // 2.消息提示
      if (createUserRes.code === 0) {
        // 2.1新建成功
        notification('success', createUserRes.data)
        // 2.2请求新的数据
        this.postUsersListDataAction({ size: 10, offset: 0 })
      } else {
        //2.3新建失败
        notification('error', createUserRes.data)
      }
    },
    //编辑用户
    async editUserDataAction(id: number, userInfo: any) {
      // 1.调用接口
      const editUserRes = await editUserData(id, userInfo)
      // 2.消息提示
      if (editUserRes.code === 0) {
        // 2.1编辑成功
        notification('success', editUserRes.data)
        // 2.2请求新的数据
        this.postUsersListDataAction({ size: 10, offset: 0 })
      } else {
        //2.3编辑失败
        notification('error', editUserRes.data)
      }
    }
  }
})

export default useUserStore
